package com.yuncheng.spcyApi.controller;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.entity.SpcyRsJjrk;
import com.yuncheng.spcyApi.service.ISpcyRsJjrkService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 审评查验-节假日库
 * @Author: csx
 * @Date: 2023-03-03
 * @Version: V1.0
 */
@Api(tags = "审评查验-节假日库接口")
@RestController
@RequestMapping("/api/spzx-spcy/spcyRsJjrk")
public class SpcyRsJjrkController extends BaseController<SpcyRsJjrk, ISpcyRsJjrkService> {

    private static final Logger log = LoggerFactory.getLogger(SpcyRsJjrkController.class);

    @Resource
    private ISpcyRsJjrkService spcyRsJjrkService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Resource
    private ISpcyLogService spcyLogService;

    /**
     * 分页列表查询
     *
     * @param spcyRsJjrk
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Log(title = "审评查验-节假日库-分页列表查询")
    @ApiOperation(value = "审评查验-节假日库-分页列表查询")
    @GetMapping(value = "/list")
    public HttpResult<?> queryPageList(SpcyRsJjrk spcyRsJjrk, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SpcyRsJjrk> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<SpcyRsJjrk> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsJjrk.getFyear()),SpcyRsJjrk::getFyear,spcyRsJjrk.getFyear());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsJjrk.getFjjrmc()),SpcyRsJjrk::getFjjrmc,spcyRsJjrk.getFjjrmc());
        queryWrapper.eq(StringUtils.isNotEmpty(spcyRsJjrk.getFjjrlx()),SpcyRsJjrk::getFjjrlx,spcyRsJjrk.getFjjrlx());
        if (spcyRsJjrk.getFjjrsj() != null) {
            queryWrapper.eq(SpcyRsJjrk::getFjjrsj, spcyRsJjrk.getFjjrsj());
        }
        queryWrapper.orderByDesc(SpcyRsJjrk::getFjjrsj);
        IPage<SpcyRsJjrk> pageList = spcyRsJjrkService.page(page, queryWrapper);
        return HttpResult.ok(pageList);
    }



    /**
     * 添加
     *
     * @param spcyRsJjrk
     * @return
     */
    @Log(title = "审评查验-节假日库-添加")
    @ApiOperation(value = "审评查验-节假日库-添加")
    @PostMapping(value = "/add")
    public HttpResult<?> add(@RequestBody SpcyRsJjrk spcyRsJjrk) {
        spcyRsJjrkService.save(spcyRsJjrk);
        String operContent = "新增信息：";

        // 将map里面的属性和值转String
        Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(spcyRsJjrk);
        operContent += LogUtils.MapToStringMethod(beanMap);
        spcyLogService.addLogs(LogConstant.LOGS_RS_JJRK,operContent,spcyRsJjrk.getId(), LogConstant.LOGS_RS_JJRK, SpcyConstant.LOGS_SYS_TYPE_XZ);
        return HttpResult.ok("添加成功");
    }

    /**
     * 编辑
     *
     * * @return
     */
    @Log(title = "审评查验-节假日库-编辑")
    @ApiOperation(value = "审评查验-节假日库-编辑")
    @ApiImplicitParam(name = "id",value = "节假日库id",required = true)
    @PutMapping(value = "/edit")
    public HttpResult<?> edit(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException{
        if (StringUtils.isEmpty(buffer.get("id"))){
            return HttpResult.error("节假日库信息id不能为空");
        }
        String qyId = buffer.get("id");
        SpcyRsJjrk oldJjrk = spcyRsJjrkService.getById(qyId);
        SpcyRsJjrk oldJjrkUpdate = spcyRsJjrkService.getById(qyId);
        if (oldJjrkUpdate == null){
            return HttpResult.error("当前节假日库信息数据不存在，请重试");
        }
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(oldJjrkUpdate, buffer);
        spcyRsJjrkService.updateById(oldJjrkUpdate);

        String operContent = "基本信息修改：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldJjrk);
        operContent += LogUtils.BeanModifyMsg(oldJjrkUpdate,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_RS_JJRK,operContent,qyId,LogConstant.LOGS_RS_JJRK,SpcyConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok("修改成功");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @Log(title = "审评查验-节假日库-通过id删除")
    @ApiOperation(value = "审评查验-节假日库-通过id删除")
    @DeleteMapping(value = "/delete")
    public HttpResult<?> delete(@RequestParam("id") String id) {
        if (StringUtils.isEmpty(id)){
            return HttpResult.error("id参数不能为空");
        }
        SpcyRsJjrk nowJjrk = spcyRsJjrkService.getById(id);
        if (nowJjrk == null){
            return HttpResult.error("当前节假日库信息数据不存在，请重试");
        }
        spcyRsJjrkService.removeById(id);
        String operContent = "删除信息：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(nowJjrk);
        operContent += LogUtils.MapToStringMethod(oldMap);
        spcyLogService.addLogs(LogConstant.LOGS_RS_JJRK,operContent,id,LogConstant.LOGS_RS_JJRK,SpcyConstant.LOGS_SYS_TYPE_SC);
        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     * @return
     */
    @Log(title = "审评查验-节假日库-批量删除")
    @ApiOperation(value = "审评查验-节假日库-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SpcyRsJjrk> spcyRsJjrkList = spcyRsJjrkService.listByIds(idsList);
        if (CollectionUtils.isEmpty(spcyRsJjrkList)){
            return HttpResult.error("数据不存在，请重试");
        }
        String operContent = "";
        for (SpcyRsJjrk jjrk : spcyRsJjrkList){
            String id = jjrk.getId();
            spcyRsJjrkService.removeById(id);

            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(jjrk);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_RS_JJRK,operContent,id,LogConstant.LOGS_RS_JJRK,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";
        }

        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @Log(title = "审评查验-节假日库-通过id查询")
    @ApiOperation(value = "审评查验-节假日库-通过id查询")
    @GetMapping(value = "/queryById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SpcyRsJjrk spcyRsJjrk = spcyRsJjrkService.getById(id);
        return HttpResult.ok(spcyRsJjrk);
    }

    /**
     * 数据转换
     * @param spcyRsJjrk
     */
    private void formatValue(SpcyRsJjrk spcyRsJjrk){
    }

    /**
     * 导入节假日库数据-表格excel
     */
    @Log(title = "导入节假日库数据-表格excel")
    @ApiOperation(value = "导入节假日库数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "excel模板文件",required = true),
    })
    @PostMapping(value = "impRsJjrkData")
    public HttpResult<?> impRsJjrkData(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);
        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_RS_JJRK_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入节假日库数据出错-{}",e.getMessage());
        }
        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            for (Map map : mapsList) {
                SpcyRsJjrk rsJjrk = new SpcyRsJjrk();
                String rsJjrkId = GetUuIdUtils.NotReplaceUuId();
                BeanUtil.copyProperties(map,rsJjrk);
                rsJjrk.setId(rsJjrkId);
                spcyRsJjrkService.save(rsJjrk);
            }
        }
        fileUpload.delete();
        return HttpResult.ok("导入成功");
    }

    /**
     * 下载节假日库-导入模板
     * @param response
     */
    @Log(title = "下载节假日库-导入模板")
    @ApiOperation(value = "下载节假日库-导入模板")
    @GetMapping("/downRsJjrkTemplate")
    public void downRsJjrkTemplate(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("JjrkImpTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.IMPORT_RS_JJRK_XML, out);
        } catch (Exception e) {
            log.error("下载节假日库模板错误-{}",e.getMessage());
        }
    }

    /**
     * 导出节假日库数据-表格excel
     */
    @Log(title = "导出节假日库数据-表格excel")
    @ApiOperation(value = "导出节假日库数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "节假日库id字符逗号分割",dataType = "String")
    })
    @GetMapping("/exportRsJjrkData")
    public void exportRsJjrkData(@RequestParam(value = "ids",defaultValue = "")String ids,
                                SpcyRsJjrk spcyRsJjrk,
                                HttpServletResponse response){
        try {
            String name = "exportRsJjrk";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<String> IdsList = Arrays.asList(ids.split(","));
            List<Object> list = new ArrayList<>(); // 导出的数据
            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                List<SpcyRsJjrk> rsJjrkList = spcyRsJjrkService.listByIds(IdsList);
                if (CollectionUtils.isNotEmpty(rsJjrkList)){
                    for (SpcyRsJjrk e : rsJjrkList){
                        list.add(e);
                    }
                }
            }else {
                LambdaQueryWrapper<SpcyRsJjrk> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsJjrk.getFyear()),SpcyRsJjrk::getFyear,spcyRsJjrk.getFyear());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsJjrk.getFjjrmc()),SpcyRsJjrk::getFjjrmc,spcyRsJjrk.getFjjrmc());
                queryWrapper.eq(StringUtils.isNotEmpty(spcyRsJjrk.getFjjrlx()),SpcyRsJjrk::getFjjrlx,spcyRsJjrk.getFjjrlx());
                if (spcyRsJjrk.getFjjrsj() != null) {
                    queryWrapper.eq(SpcyRsJjrk::getFjjrsj, spcyRsJjrk.getFjjrsj());
                }
                queryWrapper.orderByDesc(SpcyRsJjrk::getFjjrsj);
                List<SpcyRsJjrk> rsJjrkList = spcyRsJjrkService.list(queryWrapper);
                if (CollectionUtils.isNotEmpty(rsJjrkList)){
                    for (SpcyRsJjrk e : rsJjrkList){
                        list.add(e);
                    }
                }
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.IMPORT_RS_JJRK_XML,list,out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出节假日库数据出错-{}",e.getMessage());
        }
    }

}
